package com.dataimport.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dataimport.entity.sourceentity.StudentQualityEducationInfo;
import com.dataimport.entity.targetentity.QualityIntegrate;
import com.dataimport.entity.targetentity.SchoolCalendar;
import com.dataimport.mapper.InsertSchoolCalendarMapper;
import com.dataimport.mapper.QualityIntegrateMapper;
import com.dataimport.mapper.StudentQualityEducationInfoMapper;
import com.dataimport.service.QualityIntegrateService;
import com.dataimport.utils.HasNullFieldUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 卑微小峰
 * @date 2022/9/27
 */
@Service
public class QualityIntegrateServiceImpl extends ServiceImpl<QualityIntegrateMapper, QualityIntegrate> implements QualityIntegrateService {

    private static long PAGE_SIZE = 1000;

    private Cache<String, Long> fifoCache;

    @Autowired
    private StudentQualityEducationInfoMapper studentQualityEducationInfo;

    @Autowired
    private InsertSchoolCalendarMapper insertSchoolCalendarMapper;

    @Override
    public void dealWithQualityIntegrate() {

        List<SchoolCalendar> schoolCalendarList = insertSchoolCalendarMapper.selectList(null);
        fifoCache = CacheUtil.newFIFOCache(schoolCalendarList.size());
        for (SchoolCalendar schoolCalendar : schoolCalendarList) {
            String key = schoolCalendar.getSchoolYear().trim().replace(" ", "") + "-" + schoolCalendar.getSemester();
            fifoCache.put(key, schoolCalendar.getId());
        }

        long currentPage = 0L;
        while (true) {
            currentPage++;
            List<QualityIntegrate> qualityIntegrateList = selectData(currentPage);
            if (ObjectUtils.isEmpty(qualityIntegrateList)) {
                break;
            }
            insertData(qualityIntegrateList);
        }
    }

    public List<QualityIntegrate> selectData(long currentPage) {
        DynamicDataSourceContextHolder.push("mysql2");
        IPage<StudentQualityEducationInfo> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(PAGE_SIZE);
        IPage<StudentQualityEducationInfo> data = studentQualityEducationInfo.selectPage(page, null);
        DynamicDataSourceContextHolder.poll();

        List<StudentQualityEducationInfo> studentQualityEducationInfoList = data.getRecords();

        List<QualityIntegrate> qualityIntegrateList = studentQualityEducationInfoList.stream()
                .filter(studentQualityEducationInfo -> HasNullFieldUtil.inExistenceNull(studentQualityEducationInfo))
                .map(studentQualityEducationInfo -> {
                    QualityIntegrate qualityIntegrate = new QualityIntegrate();
                    BeanUtils.copyProperties(studentQualityEducationInfo, qualityIntegrate);

                    Long calendarId;
                    if ("01".equals(studentQualityEducationInfo.getSemester())) {
                        String key = studentQualityEducationInfo.getSchoolYear().trim().replace(" ", "") + "-0";
                        calendarId = fifoCache.get(key);
                    } else if ("02".equals(studentQualityEducationInfo.getSemester())) {
                        String key = studentQualityEducationInfo.getSchoolYear().trim().replace(" ", "") + "-1";
                        calendarId = fifoCache.get(key);
                    } else {
                        return null;
                    }

                    qualityIntegrate.setCalendarId(calendarId);
                    return qualityIntegrate;
                })
                .collect(Collectors.toList());

        return qualityIntegrateList;
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertData(List<QualityIntegrate> qualityIntegrateList) {
        try {
            DynamicDataSourceContextHolder.push("mysql1");
            this.saveBatch(qualityIntegrateList, qualityIntegrateList.size());
            DynamicDataSourceContextHolder.poll();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}
